#include "EventSystem.h"

// EventDispatcher 实现

void EventDispatcher::addEventListener(const std::string& eventType, EventListener listener) {
    std::lock_guard<std::mutex> lock(mutex);
    listeners[eventType].push_back(std::move(listener));
}

void EventDispatcher::removeEventListener(const std::string& eventType) {
    std::lock_guard<std::mutex> lock(mutex);
    listeners.erase(eventType);
}

void EventDispatcher::dispatchEvent(const std::shared_ptr<Event>& event) {
    if (!event) return;
    
    std::string eventType = event->getType();
    std::vector<EventListener> eventListeners;
    
    {
        std::lock_guard<std::mutex> lock(mutex);
        auto it = listeners.find(eventType);
        if (it != listeners.end()) {
            eventListeners = it->second;
        }
    }
    
    // 在锁外调用监听器，避免死锁
    for (const auto& listener : eventListeners) {
        if (listener) {
            listener(event);
        }
    }
}

bool EventDispatcher::hasEventListener(const std::string& eventType) const {
    std::lock_guard<std::mutex> lock(const_cast<std::mutex&>(mutex));
    auto it = listeners.find(eventType);
    return it != listeners.end() && !it->second.empty();
}

// NoticeCenter 实现

NoticeCenter& NoticeCenter::getInstance() {
    static NoticeCenter instance;
    return instance;
}

void NoticeCenter::addListener(const std::string& eventType, EventListener listener) {
    dispatcher.addEventListener(eventType, std::move(listener));
}

void NoticeCenter::removeListener(const std::string& eventType) {
    dispatcher.removeEventListener(eventType);
}

void NoticeCenter::postEvent(const std::shared_ptr<Event>& event) {
    dispatcher.dispatchEvent(event);
}